<?php
require_once 'config.php';

class Main {
	public function __call($name, $params) {
		echo new JSONResponse(JSONResponse::TYPE_ERROR, 'Method not allowed nor implemented', 0);
		exit;
	}
	
	public function test($params, $id) {
		echo new JSONResponse(JSONResponse::TYPE_TEXTMSG, array('s'=>$params[0]+$params[1]), $id);
		exit;
	}
	
	public function connect($params, $id) {
		$imap = new IMAP($params->user, $params->pass);
		$res = $imap->connectAndLogin();
		if(!$res) {
			echo new JSONResponse(JSONResponse::TYPE_ERROR, 'Wrong login/password', $id);
			exit;
		}
		return $imap;
	}
	
	public function listMailboxes($params, $id) {
		$imap = $this->connect($params, $id);
		$arr1 = $imap->listMailboxes();
		$arr2 = array();
		foreach ($arr1 as $box) {
			$arr2[$box] = $imap->getMailboxInfo($box);
		}
		echo new JSONResponse(JSONResponse::TYPE_TEXTMSG, array('info'=>$arr2), $id);
	}
	
	public function listMailboxMessages($params, $id) {
		$imap = $this->connect($params, $id);
		$mailboxInfo = $imap->getMailboxInfo($params->mailbox);
		$messagesInfo = array();
		if(0<$mailboxInfo['EXISTS']) {
			for($i=1; $i<=$mailboxInfo['EXISTS']; $i++) {
				$messagesInfo[] = $imap->getMailHeader($i)->toArray();
			}
		}
		echo new JSONResponse(JSONResponse::TYPE_TEXTMSG, array('info'=>$mailboxInfo, 'msgs'=>$messagesInfo), $id);
	}
	
	public function showMessage($params, $id) {
		$imap = $this->connect($params, $id);
		$mailboxInfo = $imap->getMailboxInfo($params->mailbox);
		$message = $imap->getMailContent($params->mailNo);
		echo new JSONResponse(JSONResponse::TYPE_TEXTMSG, array('content'=>$message->toArray()), $id);
	}
}
$jsonRequest = @json_decode($_GET['req']);

if(!$jsonRequest ||
	!$jsonRequest->jsonrpc ||
	!$jsonRequest->id ||
	!$jsonRequest->method) {
	echo new JSONResponse(JSONResponse::TYPE_ERROR, 'Request parse error', 0);
	exit;
}

$main = new Main();

$main->{$jsonRequest->method}($jsonRequest->params,$jsonRequest->id);
